﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace SqlServerDataTableToExcel.DAL
{
     public  class SqlServer : IDAL.ISqlFuc
    {

        public List<string> GetDataSourceList(string IpAddress, string UserName, string UserPwd)
        {
            List<string> rtn = new List<string>();
            string DataSource = "master";

            DBhelper.SqlServerDBHelper Dbhelper = new DBhelper.SqlServerDBHelper(IpAddress, DataSource, UserName, UserPwd);
            string Sql = "SELECT name  FROM  sys.databases";
            DataTable dt = Dbhelper.GetUsrDataSource(Sql);
            foreach (DataRow dr in dt.Rows)
            {
                rtn.Add(dr["name"].ToString());
            }
            return rtn;
        }
        public   List<Model.DataTableMsg> GetTableMsg(string IPAddress, string DataSource, string UserName,string Pwd)
        {
            DBhelper.SqlServerDBHelper Dbhelper = new DBhelper.SqlServerDBHelper(IPAddress, DataSource, UserName, Pwd);

            List<Model.DataTableMsg> rtn = new List<Model.DataTableMsg>();
            string SQL = @"SELECT name,
       CASE
           WHEN type = 'U' THEN
               '表'
           WHEN type = 'V' THEN
               '视图'
           ELSE
               '其他'
       END AS TYPE,
       object_id AS ID,
       TableDes
FROM sys.objects
    LEFT JOIN
    (
        SELECT value AS TableDes,
               major_id
        FROM sys.extended_properties
        WHERE minor_id = 0
              AND name = 'MS_Description'
    ) b
        ON sys.objects.object_id = b.major_id
WHERE TYPE IN ( 'U', 'V' )
ORDER BY TYPE,
         name;";
            DataTable tbNames = Dbhelper.GetUsrDataSource(SQL);

            SQL = @"SELECT  obj.name AS 表名 ,
        col.colorder AS 序号 ,
        col.name AS 列名 ,
        ISNULL(ep.[value], '') AS 列说明 ,
        t.name AS 数据类型 ,
        col.length AS 长度 ,
        ISNULL(COLUMNPROPERTY(col.id, col.name, 'Scale'), 0) AS 小数位数 ,
        CASE WHEN COLUMNPROPERTY(col.id, col.name, 'IsIdentity') = 1 THEN '1'
             ELSE ''
        END AS 标识 ,
        CASE WHEN EXISTS ( SELECT   1
                           FROM     dbo.sysindexes si
                                    INNER JOIN dbo.sysindexkeys sik ON si.id = sik.id
                                                              AND si.indid = sik.indid
                                    INNER JOIN dbo.syscolumns sc ON sc.id = sik.id
                                                              AND sc.colid = sik.colid
                                    INNER JOIN dbo.sysobjects so ON so.name = si.name
                                                              AND so.xtype = 'PK'
                           WHERE    sc.id = col.id
                                    AND sc.colid = col.colid ) THEN 1
             ELSE 0
        END AS 主键 ,
        CASE WHEN col.isnullable = 1 THEN 1
             ELSE 0
        END AS 允许空 ,
        ISNULL(comm.text, '') AS 默认值
FROM    dbo.syscolumns col
        LEFT  JOIN dbo.systypes t ON col.xtype = t.xusertype
        INNER JOIN dbo.sysobjects obj ON col.id = obj.id
                                         AND obj.xtype IN ( 'U','V')
                                         AND obj.status >= 0
        LEFT  JOIN dbo.syscomments comm ON col.cdefault = comm.id
        LEFT  JOIN sys.extended_properties ep ON col.id = ep.major_id
                                                 AND col.colid = ep.minor_id
                                                 AND ep.name = 'MS_Description'
        LEFT  JOIN sys.extended_properties epTwo ON obj.id = epTwo.major_id
                                                    AND epTwo.minor_id = 0
                                                    AND epTwo.name = 'MS_Description'
WHERE   obj.name IN (SELECT name   FROM sys.objects  WHERE type IN ( 'U','V'))
ORDER BY  obj.name, col.colorder;";
            DataTable dt = Dbhelper.GetUsrDataSource(SQL);
          

            for (int i = 0; i < tbNames.Rows.Count; i++)
            {
                Model.DataTableMsg table = new Model.DataTableMsg();
                table.TableName = tbNames.Rows[i]["name"].ToString();
                table.TableType = tbNames.Rows[i]["TYPE"].ToString();
                table.TableID = tbNames.Rows[i]["ID"].ToString();
                table.TableExplain = tbNames.Rows[i]["TableDes"].ToString();

                DataRow[] drs = dt.Select(string.Format("表名 = '{0}'", table.TableName));
                if (drs.Length == 0)
                {
                    continue;
                }
                for (int j = 0; j < drs.Length; j++)
                {
                    Model.TableCol tblCol = new Model.TableCol();
                    tblCol.ColName = drs[j]["列名"].ToString();
                    tblCol.ColType = drs[j]["数据类型"].ToString();
                    tblCol.ColLength = drs[j]["长度"].ToString();
                    tblCol.decimalLength = drs[j]["小数位数"].ToString();
                    tblCol.ColNull = Convert.ToBoolean(drs[j]["允许空"]);
                    tblCol.ColDefault = drs[j]["默认值"].ToString();
                    tblCol.ISKey = Convert.ToBoolean(drs[j]["主键"]);
                    tblCol.ColExp = drs[j]["列说明"].ToString();
                    table.TableCols.Add(tblCol);
                    if (tblCol.ISKey)
                    {
                        if (!string.IsNullOrWhiteSpace(table.KeyName))
                        {
                            table.KeyName += ";";
                        }
                        table.KeyName += tblCol.ColName;

                    }

                }
                rtn.Add(table);
            }

            return rtn;
        }

    }
}
